package ro.licenta.main;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import ro.licenta.room.bedroom.BedroomDialog;
import ro.licenta.room.funroom.FunroomDialog;
import ro.licenta.room.kitchen.FridgeDialog;
import ro.licenta.tama.Tama;
import ro.licenta.utilities.interfaces.ActivityInterface;
import ro.licenta.utilities.receiver.MyUpdateBroadcastReceiver;
import ro.licenta.utilities.services.MyService;
import ro.licenta.utilities.utils.PreferencesUtils;
import ro.licenta.utilities.utils.StaticUtils;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.example.test.R;

public class MainActivity extends Activity implements OnTouchListener,
		OnGestureListener, ActivityInterface {

	private GestureDetector gestureScanner;
	private static final int SWIPE_MIN_DISTANCE = 120;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private ViewFlipper vf;
	private PreferencesUtils mPrefs;
	private Tama tTama;
	private IntentFilter filter;
	private static MyUpdateBroadcastReceiver updateReceiver;
	private ImageView ivTamaKitchen, ivTamaBedroom, ivTamaFunroom,
			ivFunroom_toy, ivFunroom_chest, ivKitchen_food, ivKitchen_fridge,
			ivBedroom_chest, ivBedroom_lamp, ivBedroom_bed, ivBedroom_toy;
	private int resultRoom, resultPosition;
	private Intent service;
	private Calendar oldCalendarFull, oldCalendarFun;
	
	@Override
	protected void onStart() {
		
		// TODO Auto-generated method stub
		if ((updateReceiver == null) && (!tTama.isDead())) {
			filter = new IntentFilter(StaticUtils.ACTION_RESP);
			filter.addCategory(Intent.CATEGORY_DEFAULT);
			updateReceiver = new MyUpdateBroadcastReceiver(this);
			registerReceiver(updateReceiver, filter);
		}
		if ((!isMyServiceRunning()) && (!tTama.isDead())) {
			startService(service);
		}
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		if (updateReceiver != null)
			unregisterReceiver(updateReceiver);
		updateReceiver = null;
		super.onStop();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		oldCalendarFull = Calendar.getInstance();
		oldCalendarFun = Calendar.getInstance();
		mPrefs = new PreferencesUtils(this);
		tTama = Tama.getInstance();

		service = new Intent(this, MyService.class);

		gestureScanner = new GestureDetector(this, this);

		vf = (ViewFlipper) findViewById(R.id.vf_main);
		tTama.setResultRoom(vf.getDisplayedChild());
		ivTamaKitchen = (ImageView) findViewById(R.id.iv_tama_kitchen);
		ivKitchen_food = (ImageView) findViewById(R.id.iv_kitchen_food);
		ivTamaBedroom = (ImageView) findViewById(R.id.iv_tama_bedroom);
		ivTamaFunroom = (ImageView) findViewById(R.id.iv_tama_funroom);
		ivFunroom_toy = (ImageView) findViewById(R.id.iv_funroom_toy);
		if (Build.VERSION.SDK_INT >= 11) {
			ivTamaKitchen.setOnDragListener(myDragListener);
			ivKitchen_food.setOnTouchListener(myTouchListener);
			ivTamaFunroom.setOnDragListener(myDragListener);
			ivFunroom_toy.setOnTouchListener(myTouchListener);
		} else {
			ivKitchen_food.setOnClickListener(myClickListener);
			ivFunroom_toy.setOnClickListener(myClickListener);
		}

		ivKitchen_fridge = (ImageView) findViewById(R.id.iv_kitchen_fridge);
		ivBedroom_chest = (ImageView) findViewById(R.id.iv_bedroom_chest);
		ivBedroom_lamp = (ImageView) findViewById(R.id.iv_bedroom_lamp);
		ivBedroom_lamp.setVisibility(View.GONE);
		ivBedroom_bed = (ImageView) findViewById(R.id.iv_bedroom_bed);
		ivBedroom_bed.setVisibility(View.GONE);
		ivBedroom_toy = (ImageView) findViewById(R.id.iv_bedroom_toy);
		ivBedroom_toy.setVisibility(View.GONE);
		ivFunroom_chest = (ImageView) findViewById(R.id.iv_funroom_chest);

		ivKitchen_fridge.setOnClickListener(myClickListener);
		ivBedroom_chest.setOnClickListener(myClickListener);
		ivBedroom_lamp.setOnClickListener(myClickListener);
		ivFunroom_chest.setOnClickListener(myClickListener);

		System.out.println("OnCreateActivity");
	}

	@Override
	protected void onResume() {
		tTama = Tama.getInstance();
		if (tTama.getLampPosition() != StaticUtils.error)
			ivBedroom_lamp.setImageResource(StaticUtils.bedroomResourceId[tTama
					.getLampPosition()]);
		if (tTama.getBedPosition() != StaticUtils.error)
			ivBedroom_bed.setImageResource(StaticUtils.bedroomResourceId[tTama
					.getBedPosition()]);
		if (tTama.getStuffPosition() != StaticUtils.error)
			ivBedroom_toy.setImageResource(StaticUtils.bedroomResourceId[tTama
					.getStuffPosition()]);

		if (tTama.getToyPosition() != StaticUtils.error) {
			ivFunroom_toy.setImageResource(StaticUtils.funroomResourceId[tTama
					.getToyPosition()]);
		}
		if (tTama.getFoodPosition() != StaticUtils.error) {
			ivKitchen_food.setImageResource(StaticUtils.kitchenResourceId[tTama
					.getFoodPosition()]);
		}

		updateUi();
		System.out.println("OnResumeActivity");
		super.onResume();
	}

	@Override
	protected void onPause() {

		System.out.println("OnPauseActivity");
		super.onPause();
	}

	@Override
	protected void onDestroy() {

		if (isMyServiceRunning()) {
			stopService(service);
		}
		if ((updateReceiver != null) && (tTama.isDead()))
			unregisterReceiver(updateReceiver);
		updateReceiver = null;
		System.out.println("OnDestroyActivity");
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		tTama = Tama.getInstance();

		if (requestCode == 1) {

			if (resultCode == RESULT_OK) {

				resultPosition = data.getIntExtra(StaticUtils.positionId, -1);
				if (resultPosition != -1) {
					resultRoom = data.getIntExtra(StaticUtils.roomId, -1);
					if (resultRoom != -1) {
						if (resultRoom == StaticUtils.roomKitchen) {
							ivKitchen_food
									.setImageResource(StaticUtils.kitchenResourceId[resultPosition]);
							ivKitchen_food.setVisibility(View.VISIBLE);
							tTama.setFoodPosition(resultPosition);
							// tTama.setResultRoom(resultRoom);
						}
						if (resultRoom == StaticUtils.roomBedroom) {
							// get beds
							// tTama.setResultRoom(resultRoom);
							if ((resultPosition >= 0) && (resultPosition <= 2)) {
								ivBedroom_bed
										.setImageResource(StaticUtils.bedroomResourceId[resultPosition]);
								ivBedroom_bed.setVisibility(View.VISIBLE);
								tTama.setBedPosition(resultPosition);
							}
							// get lamps
							if ((resultPosition >= 3) && (resultPosition <= 5)) {
								ivBedroom_lamp
										.setImageResource(StaticUtils.bedroomResourceId[resultPosition]);
								ivBedroom_lamp.setVisibility(View.VISIBLE);
								tTama.setLampPosition(resultPosition);
							}
							// get sleeping-stuff
							if (resultPosition >= 6) {
								ivBedroom_toy
										.setImageResource(StaticUtils.bedroomResourceId[resultPosition]);
								ivBedroom_toy.setVisibility(View.VISIBLE);
								tTama.setStuffPosition(resultPosition);
							}
						}
						if (resultRoom == StaticUtils.roomFunroom) {
							ivFunroom_toy
									.setImageResource(StaticUtils.funroomResourceId[resultPosition]);
							ivFunroom_toy.setVisibility(View.VISIBLE);
							tTama.setToyPosition(resultPosition);
							// tTama.setResultRoom(resultRoom);
						}
					}
				}
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private OnClickListener myClickListener = new OnClickListener() {
		public void onClick(View v) {
			tTama = Tama.getInstance();
			switch (v.getId()) {
			case R.id.iv_kitchen_fridge: {
				Intent intent = new Intent(MainActivity.this,
						FridgeDialog.class);
				startActivityForResult(intent, 1);
				break;
			}
			case R.id.iv_bedroom_chest: {
				Intent intent = new Intent(MainActivity.this,
						BedroomDialog.class);
				startActivityForResult(intent, 1);
				break;
			}
			case R.id.iv_funroom_chest: {
				Intent intent = new Intent(MainActivity.this,
						FunroomDialog.class);
				startActivityForResult(intent, 1);
				break;
			}
			case R.id.iv_bedroom_lamp: {
				if ((tTama.getStuffPosition() != StaticUtils.error)
						&& (tTama.getBedPosition() != StaticUtils.error)) {
					WindowManager.LayoutParams layout = getWindow()
							.getAttributes();
					if (!tTama.isSleeping()) {
						layout.screenBrightness = 0.1F;
						ivBedroom_lamp.setImageResource(R.drawable.bed_lamp1);
						tTama.setSleeping(true);
						ivKitchen_food.setOnClickListener(myDummyClickListener);
						ivKitchen_fridge
								.setOnClickListener(myDummyClickListener);
						ivBedroom_chest
								.setOnClickListener(myDummyClickListener);
						ivFunroom_chest
								.setOnClickListener(myDummyClickListener);
						ivFunroom_toy.setOnClickListener(myDummyClickListener);
					} else {
						ivBedroom_lamp.setImageResource(R.drawable.bed_lamp2);
						layout.screenBrightness = 1.0F;
						tTama.setSleeping(false);
						ivKitchen_fridge.setOnClickListener(myClickListener);
						ivBedroom_chest.setOnClickListener(myClickListener);
						ivBedroom_lamp.setOnClickListener(myClickListener);
						ivFunroom_chest.setOnClickListener(myClickListener);
						if (Build.VERSION.SDK_INT >= 11) {
							ivTamaKitchen.setOnDragListener(myDragListener);
							ivKitchen_food.setOnTouchListener(myTouchListener);
							ivTamaFunroom.setOnDragListener(myDragListener);
							ivFunroom_toy.setOnTouchListener(myTouchListener);
						} else {
							ivKitchen_food.setOnClickListener(myClickListener);
							ivFunroom_toy.setOnClickListener(myClickListener);
						}
					}
					getWindow().setAttributes(layout);
				} else if (tTama.getBedPosition() == StaticUtils.error) {
					Toast.makeText(MainActivity.this,
							"Please pick a bed to sleep on!",
							Toast.LENGTH_SHORT).show();
				} else if (tTama.getStuffPosition() == StaticUtils.error) {
					Toast.makeText(MainActivity.this,
							"Please pick a toy to sleep with!",
							Toast.LENGTH_SHORT).show();
				}
				break;
			}
			case R.id.iv_kitchen_food: {
				tTama.modifyFull(StaticUtils.kitchenFull[resultPosition]);
				tTama.modifyHp();
				ivKitchen_food.setVisibility(View.GONE);
				updateUi();
				break;
			}
			case R.id.iv_funroom_toy: {
				Intent intent = new Intent(MainActivity.this,
						FunroomDialog.class);
				startActivityForResult(intent, 1);
				break;
			}
			default:
				break;
			}
		}
	};

	private OnClickListener myDummyClickListener = new OnClickListener() {
		public void onClick(View v) {
		}
	};

	private OnTouchListener myTouchListener = new OnTouchListener() {
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
				ClipData data = ClipData.newPlainText("", "");
				DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
						view);
				view.startDrag(data, shadowBuilder, view, 0);
				view.setVisibility(View.INVISIBLE);
				return true;
			} else {
				return false;
			}
		}
	};

	private OnDragListener myDragListener = new OnDragListener() {

		public boolean onDrag(View v, DragEvent event) {
			tTama = Tama.getInstance();
			switch (event.getAction()) {
			case DragEvent.ACTION_DRAG_STARTED:
				break;
			case DragEvent.ACTION_DRAG_ENTERED:
				break;
			case DragEvent.ACTION_DRAG_EXITED:
				break;
			case DragEvent.ACTION_DROP: {

				switch (tTama.getResultRoom()) {
				case StaticUtils.roomKitchen: {
					Calendar currentCalendar = Calendar.getInstance();
					Date oldDate = oldCalendarFull.getTime();
					Date currentDate = currentCalendar.getTime();
					long currentdiffInMillis = currentDate.getTime()
							- oldDate.getTime();
					long diff;
					if (tTama.isThesys())
						diff = StaticUtils.feedIntervalThesys;
					else
						diff = StaticUtils.feedInterval;
					if ((currentdiffInMillis / 1000) >= diff) {
						tTama.modifyFull(StaticUtils.kitchenFull[tTama
								.getFoodPosition()]);
						tTama.modifyHp();
						oldCalendarFull = currentCalendar;
						Toast.makeText(getApplicationContext(), "Yummy!",
								Toast.LENGTH_SHORT).show();
						tTama.setFed(true);
					} else {
						Toast.makeText(getApplicationContext(),
								"I don't want to eat more.", Toast.LENGTH_SHORT)
								.show();
						tTama.setFed(false);
					}
					break;
				}
				case StaticUtils.roomFunroom: {
					Calendar currentCalendar = Calendar.getInstance();
					Date oldDate = oldCalendarFun.getTime();
					Date currentDate = currentCalendar.getTime();
					long currentdiffInMillis = currentDate.getTime()
							- oldDate.getTime();
					long diff;
					if (tTama.isThesys())
						diff = StaticUtils.feedIntervalThesys;
					else
						diff = StaticUtils.feedInterval;
					if ((currentdiffInMillis / 1000) >= diff) {
						tTama.modifyFun(StaticUtils.funroomFun[tTama
								.getToyPosition()]);
						tTama.modifyHp();
						oldCalendarFun = currentCalendar;
						Toast.makeText(
								getApplicationContext(),
								"I love playing with my "
										+ StaticUtils.funroomResourceName[tTama
												.getToyPosition()],
								Toast.LENGTH_SHORT).show();
						tTama.setFed(true);
					} else {
						Toast.makeText(getApplicationContext(),
								"I don't want to play no more.",
								Toast.LENGTH_SHORT).show();
						tTama.setFed(false);
					}

					break;
				}
				default: {
					break;
				}
				}
				updateUi();
				break;
			}
			case DragEvent.ACTION_DRAG_ENDED: {
				switch (tTama.getResultRoom()) {
				case StaticUtils.roomKitchen: {
					if (!event.getResult()) {
						ivKitchen_food
								.setImageResource(StaticUtils.kitchenResourceId[tTama
										.getFoodPosition()]);
						ivKitchen_food.setVisibility(View.VISIBLE);
					} else if (tTama.isFed()) {
						ivKitchen_food.setVisibility(View.GONE);
						tTama.setFed(false);
						tTama.setFoodPosition(StaticUtils.error);
					} else {
						ivKitchen_food
								.setImageResource(StaticUtils.kitchenResourceId[tTama
										.getFoodPosition()]);
						ivKitchen_food.setVisibility(View.VISIBLE);

					}
					break;
				}
				case StaticUtils.roomFunroom: {
					ivFunroom_toy
							.setImageResource(StaticUtils.funroomResourceId[tTama
									.getToyPosition()]);
					ivFunroom_toy.setVisibility(View.VISIBLE);

					break;
				}
				}
				break;
			}
			default:
				break;
			}

			return true;
		}
	};

	public void updateUi() {
		(new UpdateTask()).execute();
	}

	private class UpdateTask extends AsyncTask<Void, Void, Void> {
		int tHp, tFun, tEne, tFull, tAge;

		@Override
		protected Void doInBackground(Void... params) {
			tTama = Tama.getInstance();
			tHp = tTama.getHp() / 10;
			tFun = tTama.getFun() / 10;
			tEne = tTama.getEne() / 10;
			tFull = tTama.getFull() / 10;
			tAge = tTama.getAge();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			tTama = Tama.getInstance();
			TextView tv_hp = (TextView) findViewById(R.id.tv_tama_hp);
			int id_hp = getResources().getIdentifier("tama_hp" + tHp,
					"drawable", getPackageName());
			tv_hp.setBackgroundResource(id_hp);
			System.out.println("hp " + tTama.getHp());

			TextView tv_full = (TextView) findViewById(R.id.tv_tama_fullness);
			int id_full = getResources().getIdentifier("tama_fullness" + tFull,
					"drawable", getPackageName());
			tv_full.setBackgroundResource(id_full);
			System.out.println("full " + tTama.getFull());

			TextView tv_fun = (TextView) findViewById(R.id.tv_tama_fun);
			int id_fun = getResources().getIdentifier("tama_fun" + tFun,
					"drawable", getPackageName());
			tv_fun.setBackgroundResource(id_fun);
			System.out.println("fun " + tTama.getFun());

			TextView tv_ene = (TextView) findViewById(R.id.tv_tama_energy);
			int id_ene = getResources().getIdentifier("tama_energy" + tEne,
					"drawable", getPackageName());
			tv_ene.setBackgroundResource(id_ene);
			System.out.println("ene " + tTama.getEne());
			if (Build.VERSION.SDK_INT >= 11) {
				switch (tAge) {

				case 1: {
					ivTamaKitchen.setScaleX(1.0f);
					ivTamaKitchen.setScaleY(1.0f);
					ivTamaBedroom.setScaleX(1.0f);
					ivTamaBedroom.setScaleY(1.0f);
					ivTamaFunroom.setScaleX(1.0f);
					ivTamaFunroom.setScaleY(1.0f);
					break;
				}
				case 2: {
					ivTamaKitchen.setScaleX(1.2f);
					ivTamaKitchen.setScaleY(1.2f);
					ivTamaBedroom.setScaleX(1.2f);
					ivTamaBedroom.setScaleY(1.2f);
					ivTamaFunroom.setScaleX(1.2f);
					ivTamaFunroom.setScaleY(1.2f);
					break;
				}
				case 3: {
					ivTamaKitchen.setScaleX(1.1f);
					ivTamaKitchen.setScaleY(1.1f);
					ivTamaBedroom.setScaleX(1.1f);
					ivTamaBedroom.setScaleY(1.1f);
					ivTamaFunroom.setScaleX(1.1f);
					ivTamaFunroom.setScaleY(1.1f);
					break;
				}
				default:
					break;
				}
			}
			System.out.println("Age " + tTama.getAge());
			SimpleDateFormat parseDate = new SimpleDateFormat("hh:mm");
			Calendar calendarTest = Calendar.getInstance();
			System.out.println(parseDate.format(calendarTest.getTime()));
			System.out.println("Sleeping " + tTama.isSleeping());
			System.out.println("Dead " + tTama.isDead());
			System.out
					.println("-------------------------------------------------");

			if (tTama.isDead()) {
				ivKitchen_food.setOnClickListener(myDummyClickListener);
				ivKitchen_fridge.setOnClickListener(myDummyClickListener);
				ivBedroom_chest.setOnClickListener(myDummyClickListener);
				ivBedroom_lamp.setOnClickListener(myDummyClickListener);
				ivFunroom_chest.setOnClickListener(myDummyClickListener);
				ivFunroom_toy.setOnClickListener(myDummyClickListener);
			}
			super.onPostExecute(result);
		}
	}

	private boolean isMyServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (MyService.class.getName()
					.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.reset: {
			mPrefs.setGameStarted(false);
			Intent intent = new Intent(this, LoadingActivity.class);
			startActivity(intent);
			finish();
			return true;
		}
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public boolean onTouch(View v, MotionEvent event) {
		return false;
	}

	public void onLongPress(MotionEvent e) {
	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return true;
	}

	public void onShowPress(MotionEvent e) {
	}

	public boolean onSingleTapUp(MotionEvent e) {
		return true;
	}

	@Override
	public boolean onTouchEvent(MotionEvent me) {
		return gestureScanner.onTouchEvent(me);
	}

	public boolean onDown(MotionEvent e) {
		return true;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		try {
			tTama = Tama.getInstance();
			if (e1.getX() > e2.getX()
					&& Math.abs(e1.getX() - e2.getX()) > SWIPE_MIN_DISTANCE
					&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
				vf.showNext();
				tTama.setResultRoom(vf.getDisplayedChild());
			} else if (e1.getX() < e2.getX()
					&& e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
					&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
				vf.showPrevious();
				tTama.setResultRoom(vf.getDisplayedChild());
			}
		} catch (Exception e) {
		}
		return true;
	}
	 
}